package odgs.pda;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import odgs.Connection;
import odgs.GridNode;
import odgs.Result;
import odgs.message.Message;
import odgs.pda.receiver.ReceivedMessageHandler;
import odgs.pda.sender.SendMessageHandler;

public class PdaMessageReceiver implements Runnable {

	private Connection connection;
	private InputStream is;

	protected DocumentBuilder builder;
	private boolean isStop;

	public PdaMessageReceiver(Connection connection, InputStream is) {
		this.connection = connection;
		this.is = is;
	}

	@Override
	public void run() {
		while (!isStop) {
			try {
				BufferedInputStream bis = new BufferedInputStream(is);
				ByteArrayOutputStream headerOut = new ByteArrayOutputStream();
				headerOut.flush();

				while (true) {
					int r = bis.read();
					if (r == '\n' || r == -1)
						break;
					headerOut.write(r);
				}
				String header = new String(headerOut.toByteArray());
				System.out.println(header);

				ReceivedMessageHandler handler = getHandler(header); 

				System.out.println("Received Message : " + header);
				connection.receivedMessage(handler.getMessage());

			} catch (Exception e1) {
				connection.disconnected();
				isStop = true;
			}
		}
	}

	private ReceivedMessageHandler getHandler(String cmdMsg) {
		String path = "pda.receiver." + cmdMsg + "Receiver";
		Class clazz;
		try {
			clazz = Class.forName(path);
			return (ReceivedMessageHandler) clazz.newInstance();
		} catch (Exception e) {
			return null;
		}
	}
}